﻿using Shop.Common;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Web;
using System.Web.Http;

//using SqlSugar;

namespace Shop.Implementation.Customer
{
    public class ICustomer_V1 : Interface.Customer.ICustomer
    {
        #region 用户更改密码，先发送验证码

        public override Dictionary<string, object> ChangePassWordMSG()
        {
            string errMsg;
            string phoneNumber = System.Web.HttpContext.Current.Request.QueryString["phone"].GetVal_String();
            if (!CheckCustomerExists(phoneNumber))
            { return Common.ReturnValue.Get("手机号码不存在，请先注册", false); }
            if (!Common.HandleSMS.CheckNumber(phoneNumber, out errMsg))
            {
                return Common.ReturnValue.Get(errMsg, false);
            }
            if (!Common.HandleSMS.CheckRepeat(phoneNumber, out errMsg))
            {
                return Common.ReturnValue.Get(errMsg, false);
            }
            var openid = Common.HandleCookie.GetCookieValue("openid");
            bool bret = Common.HandleSMS.SendYZM(phoneNumber, openid, out errMsg);
            if (bret) { return Common.ReturnValue.Get("发送成功", true); }
            else { return Common.ReturnValue.Get("发送失败" + errMsg, true); }
        }

        #endregion 用户更改密码，先发送验证码

        #region 更改密码

        public override Dictionary<string, object> ChangePassWord()
        {
            string token;
            string errStr;
            NameValueCollection nv = HttpContext.Current.Request.Form;
            string PhoneNumber = nv["PhoneNumber"].GetVal_String();
            string testCode = nv["TestCode"].GetVal_String();
            string Password = nv["Password"].GetVal_String();

            if (!Common.HandleSMS.CheckYZM(PhoneNumber, testCode))
            {
                return Common.ReturnValue.Get("请输入正确的验证码", false);
            }
            if (!SaveNewPassword(PhoneNumber, Password, out errStr))
            { return Common.ReturnValue.Get(errStr, false); }
            if (!CustomerLoginCheckPassword(PhoneNumber, Password, out errStr))
            { return Common.ReturnValue.Get(errStr, false); }
            if (!CustomerLoginSaveToken(PhoneNumber, out token, out errStr))
            { return Common.ReturnValue.Get(errStr, false); }
            return Common.ReturnValue.Get(token, true);
        }

        private bool SaveNewPassword(string _mobile, string _password, out string _errStr)
        {
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    cn.Open();
                    string cmdsql = "select * from Customer (nolock) where cMobile=@mobile";
                    SqlCommand cncmd = new SqlCommand(cmdsql, cn);
                    SqlTransaction tran = cn.BeginTransaction();
                    cncmd.Transaction = tran;
                    DataTable dtjud = new DataTable();
                    cncmd.Parameters.Add(new SqlParameter("@mobile", _mobile));
                    dtjud.Load(cncmd.ExecuteReader());
                    cncmd.Parameters.Clear();
                    if (dtjud.Rows.Count == 0)
                    { _errStr = "手机号码不正确，请先注册！"; return false; }

                    cmdsql = @"update customer set cSN=@cSn,cFromIP=@cFromIP,dModiDate=getdate() where cMobile=@cMobile ";
                    cncmd.CommandText = cmdsql;
                    cncmd.Parameters.Add(new SqlParameter("@cMobile", _mobile));
                    cncmd.Parameters.Add(new SqlParameter("@cSN", _password));
                    cncmd.Parameters.Add(new SqlParameter("@cFromIP", Common.HandleLog.GetIPAddress()));
                    cncmd.ExecuteNonQuery();
                    cncmd.Parameters.Clear();

                    tran.Commit();
                    _errStr = "";
                    return true;
                }
                finally
                { cn.Close(); cn.Dispose(); }
            }
        }

        #endregion 更改密码

        #region 检查是否登陆

        public override Dictionary<string, object> CheckToken()
        {
            string _token = System.Web.HttpContext.Current.Request.QueryString["token"].GetVal_String();
            int idcus;
            bool bret = CustomerCommon.check_token(_token, out idcus);
            if (!bret) { return CustomerCommon.NotLogin(); }

            ICustomerConsignee_V1 icuscon = new ICustomerConsignee_V1();
            return icuscon.GetAll(idcus);
        }

        #endregion 检查是否登陆

        #region 用户登录

        public override Dictionary<string, object> Login()
        {
            string sToken;
            NameValueCollection nvf = HttpContext.Current.Request.Form;
            string PhoneNumber = nvf["PhoneNumber"].GetVal_String();
            string Password = nvf["Password"].GetVal_String();
            bool bret = CustomerLogin(PhoneNumber, Password, out sToken);
            return Common.ReturnValue.Get(sToken, bret);
        }

        public bool CustomerLogin(string phoneNumber, string passWord, out string token)
        {
            if (!CustomerLoginCheckPassword(phoneNumber, passWord, out token))
            { return false; }
            string errstr;
            if (!CustomerLoginSaveToken(phoneNumber, out token, out errstr))
            { return false; }
            return true;
        }

        private bool CustomerLoginCheckPassword(string _mobile, string _passWord, out string _errStr)
        {
            string cmdsql = "select isnull(cSN,'') as cSN from Customer where cMobile=@mobile";
            DataTable dt = Common.HandleSQL.GetData(cmdsql, null, new SqlParameter[] { new SqlParameter("@mobile", _mobile) });
            if (dt.Rows.Count == 0)
            {
                _errStr = "用户名不存在，请确认！";
                return false;
            }
            string passWord = dt.Rows[0][0].GetVal_String();
            if (passWord != _passWord)
            {
                _errStr = "请输入正确的密码";
                return false;
            }
            _errStr = "";
            return true;
        }

        private bool CustomerLoginSaveToken(string mobile, out string _token, out string errStr)
        {
            checktokenRepeat:
            string token = CustomerCommon.GenerateCheckCode(20);
            _token = "";
            string cmdsql = "select top 1 1 from CustomerLoginProcess (nolock) where cToken=@ctoken";
            DataTable dtjud = Common.HandleSQL.GetData(cmdsql, null, new SqlParameter[] { new SqlParameter("@ctoken", token) });
            if (dtjud.Rows.Count > 0)
            {
                goto checktokenRepeat;
            }
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    cn.Open();
                    cmdsql = "select id from Customer where cMobile=@cPhone";
                    SqlCommand cncmd = new SqlCommand(cmdsql, cn);

                    cncmd.Parameters.Add(new SqlParameter("@cPhone", mobile));
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    cncmd.Parameters.Clear();
                    int idCus = 0;
                    if (dtjud.Rows.Count > 0)
                    { idCus = dtjud.Rows[0][0].GetVal_Int(); }
                    if (idCus == 0)
                    { errStr = "客户不正确"; return false; }

                    cmdsql = "delete from CustomerLoginProcess where IDCus=" + idCus;
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    cmdsql = @"  insert into CustomerLoginProcess(IDCus,cToken,dSDate,dExpireDate)
                     values(@IDCus, @cToken, GETDATE(),dateadd(d,1,getdate()))";
                    cncmd.CommandText = cmdsql;
                    cncmd.Parameters.Add(new SqlParameter("@IDCus", idCus));
                    cncmd.Parameters.Add(new SqlParameter("@cToken", token));
                    cncmd.ExecuteNonQuery();
                    errStr = ""; _token = token;
                    return true;
                }
                finally
                { cn.Close(); cn.Dispose(); }
            }
        }

        #endregion 用户登录

        #region 新用户注册，注册完成后自动登录

        public override Dictionary<string, object> Register()
        {
            string sToken;
            NameValueCollection nvf = HttpContext.Current.Request.Form;

            string PhoneNumber = nvf["PhoneNumber"].GetVal_String();
            string testCode = nvf["TestCode"].GetVal_String();
            string Password = nvf["Password"].GetVal_String();
            string StoreName = nvf["StoreName"].GetVal_String();
            string StoreManagerName = nvf["StoreManagerName"].GetVal_String();
            string Province = nvf["Province"].GetVal_String();
            string City = nvf["City"].GetVal_String();
            string District = nvf["District"].GetVal_String();
            string Street = nvf["Street"].GetVal_String();
            string Address = nvf["Address"].GetVal_String();
            string SaleCode = nvf["SaleCode"].GetVal_String();
            double longitude = nvf["longitude"].GetVal_Double();
            double latitude = nvf["latitude"].GetVal_Double();
            string dPSTimeStart = nvf["dPSTimeStart"].GetVal_String();
            string dPSTimeEnd = nvf["dPSTimeEnd"].GetVal_String();

            if (StoreName.Length < 3 || StoreManagerName.Length < 1 || Address.Length < 3)
            {
                return Common.ReturnValue.Get("请输入正确的店铺名称，收货人，地址等信息！"
                      + StoreName + "|" + StoreName.Length + "|" + StoreManagerName + "|" + StoreManagerName.Length + "|" +
                      Address + "|" + Address.Length, false);
            }
            //if (HandleSMS.CheckWX())
            //{
            //    return ReturnValue.Get("不允许销售员代注册，请使用客户的手机注册", false);
            //}
            if (!CustomerRegisterCheckSaleCode(SaleCode))
            { return Common.ReturnValue.Get("请输入正确的销售码！", false); }
            if (!Common.HandleSMS.CheckYZM(PhoneNumber, testCode))
            { return Common.ReturnValue.Get("请输入正确的验证码", false); }
            string errStr;
            Dictionary<string, object> coupon;
            if (!SaveCustomer(PhoneNumber, Password, StoreName, StoreManagerName, Province, City, District, Street, Address, SaleCode, longitude, latitude,
                dPSTimeStart, dPSTimeEnd, out errStr, out coupon))
            { return Common.ReturnValue.Get(errStr, false); }

            #region 自动登录系统

            bool bret = CustomerLogin(PhoneNumber, Password, out sToken);

            #endregion 自动登录系统

            if (bret)
            {
                int idcus;
                CustomerCommon.check_token(sToken, out idcus);
                //var list = ICoupon_V1.GetCouponList(idcus, 1);//1是注册  2是轮播图
                if (!coupon.ContainsKey("result"))
                {
                    coupon.Add("result", 1);
                }
                if (coupon.ContainsKey("resultdetail"))
                {
                    return coupon;
                }
                coupon.Add("resultdetail", sToken);
                return coupon;
                // return ReturnValue.Get<ReceiveCoupon>(sToken, new List<ReceiveCoupon>(), bret);
            }
            return Common.ReturnValue.Get(sToken, bret);
        }

        private bool SaveCustomer(string _mobile, string _password, string _storeName, string _storeManagerName,
string Province, string City, string District, string Street, string Address, string _saleCode,
double _longitude, double _latitude, string dPSTimeStart, string dPsTimeEnd,
out string _errStr, out Dictionary<string, object> coupon)
        {
            coupon = new Dictionary<string, object>();
            bool bret = false;
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    cn.Open();
                    string cmdsql = "select * from Customer (nolock) where cMobile=@mobile";
                    SqlCommand cncmd = new SqlCommand(cmdsql, cn);
                    SqlTransaction tran = cn.BeginTransaction();
                    cncmd.Transaction = tran;
                    DataTable dtjud = new DataTable();
                    cncmd.Parameters.Add(new SqlParameter("@mobile", _mobile));
                    dtjud.Load(cncmd.ExecuteReader());
                    cncmd.Parameters.Clear();
                    if (dtjud.Rows.Count > 0)
                    { _errStr = "手机号码已经存在，请直接登录！"; return false; }

                    int maxid = 0;
                    cmdsql = "select isnull(max(id),0) from customer ";
                    cncmd.CommandText = cmdsql;
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    if (dtjud.Rows.Count > 0)
                    { maxid = (int)dtjud.Rows[0][0]; }
                    maxid += 1;
                    var openid = string.Format("{0}", Common.HandleCookie.GetCookieValue("openid"));
                    cmdsql = @"insert into customer(id,cMobile,cSN,storeName,storeManagerName,Province,City,District,Street,Address,saleCode,cFromIP,dMDate,longitude,latitude,dDate,dPSTimeStart, dPsTimeEnd,cWX )
                        values(@ID,@cMobile,@cSN,@storeName,@storeManagerName,@Province,@City,@District,@Street,@Address,@saleCode,@cFromIP,getdate(),@longitude,@latitude,convert(nvarchar,getdate(),23),@dPSTimeStart, @dPsTimeEnd,@cWX )";
                    cncmd.CommandText = cmdsql;
                    cncmd.Parameters.Add(new SqlParameter("@ID", maxid));
                    cncmd.Parameters.Add(new SqlParameter("@cMobile", _mobile));
                    cncmd.Parameters.Add(new SqlParameter("@cSN", _password));
                    cncmd.Parameters.Add(new SqlParameter("@storeName", _storeName));
                    cncmd.Parameters.Add(new SqlParameter("@storeManagerName", _storeManagerName));
                    cncmd.Parameters.Add(new SqlParameter("@Province", Province));
                    cncmd.Parameters.Add(new SqlParameter("@City", City));
                    cncmd.Parameters.Add(new SqlParameter("@District", District));
                    cncmd.Parameters.Add(new SqlParameter("@Street", Street));
                    cncmd.Parameters.Add(new SqlParameter("@Address", Address));
                    cncmd.Parameters.Add(new SqlParameter("@saleCode", _saleCode));
                    cncmd.Parameters.Add(new SqlParameter("@cFromIP", Common.HandleLog.GetIPAddress()));
                    cncmd.Parameters.Add(new SqlParameter("@longitude", _longitude));
                    cncmd.Parameters.Add(new SqlParameter("@latitude", _latitude));
                    cncmd.Parameters.Add(new SqlParameter("@dPSTimeStart", dPSTimeStart));
                    cncmd.Parameters.Add(new SqlParameter("@dPsTimeEnd", dPsTimeEnd));
                    cncmd.Parameters.Add(new SqlParameter("@cWX", openid));
                    cncmd.ExecuteNonQuery();
                    cncmd.Parameters.Clear();
                    ICustomerConsignee_V1 cuscon = new ICustomerConsignee_V1();
                    cuscon.saveCustomerConsignee(0, maxid, _storeManagerName, _mobile, 1, cncmd);
                    tran.Commit();
                    _errStr = "";
                    // 注册送券

                    #region 注册送券   领取优惠券

                    //using (SqlSugarClient db = SugarDao.GetInstance())
                    //{
                    int CouponID = 0;//现金券主键
                    int ActivityID = 0;//活动主键
                                       //获取注册送券活动信息，在有效时间内
                    var dt = HandleSQL.GetData(@"SELECT top 1 A.* FROM dbo.CouponActivity AS A INNER JOIN dbo.Coupon AS B ON A.CouponID = B.CouponID WHERE
 A.StartDate <= GETDATE() and A.EndDate+1 > GETDATE()  AND A.Name LIKE '注册送券%' ");
                    //是否还有注册送券的优惠券,有则送券
                    if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                    {
                        DataRow rw = dt.Rows[0]; CouponID = rw.Field<int>("CouponID"); ActivityID = rw.Field<int>("ActivityID");
                        //领取优惠券
                        for (int i = 0; i < dt.Rows[0].Field<int>("CouponCount"); i++)
                            coupon = ICoupon_V1.ReceivedCoupon(maxid, CouponID, ActivityID, "", 1);
                    }
                    // }

                    #endregion 注册送券   领取优惠券

                    bret = true;
                }
                finally { cn.Close(); cn.Dispose(); }
            }

            return bret;
        }

        private bool CustomerRegisterCheckSaleCode(string salecode)
        {
            string cmdsql = "select * from person (nolock) where salecode=@salecode";
            DataTable dt = Common.HandleSQL.GetData(cmdsql, null, new SqlParameter[] { new SqlParameter("@salecode", salecode) });
            if (dt.Rows.Count > 0)
            { return true; }
            else
            { return false; }
        }

        #endregion 新用户注册，注册完成后自动登录

        #region 新用户注册发送手机验证码

        public override Dictionary<string, object> RegisterSendMessage()
        {
            string errMsg;
            string phoneNumber = System.Web.HttpContext.Current.Request.QueryString["phone"].GetVal_String();

            if (!Common.HandleSMS.CheckNumber(phoneNumber, out errMsg))
            {
                return Common.ReturnValue.Get(errMsg, false);
            }
            if (CheckCustomerExists(phoneNumber))
            { return Common.ReturnValue.Get("手机号码已经注册，请直接登录即可", false); }
            if (!Common.HandleSMS.CheckRepeat(phoneNumber, out errMsg))
            {
                return Common.ReturnValue.Get(errMsg, false);
            }
            var openid = Common.HandleCookie.GetCookieValue("openid");
            bool bret = Common.HandleSMS.SendYZM(phoneNumber, openid, out errMsg);
            if (bret) { return Common.ReturnValue.Get("发送成功", true); }
            else { return Common.ReturnValue.Get("发送失败" + errMsg, true); }
        }

        private bool CheckCustomerExists(string phoneNumber)
        {
            string cmdsql = "select top 1 1 from customer where cMobile=@cMobile";
            DataTable dtjud = Common.HandleSQL.GetData(cmdsql, null,
                new SqlParameter[] { new SqlParameter("@cMobile", phoneNumber) });
            if (dtjud.Rows.Count == 0)
            { return false; }
            else
            { return true; }
        }

        #endregion 新用户注册发送手机验证码

        #region 获取用户信息

        public static CustomerINFO GetCusInfo(int idcus)
        {
            string cmdsql = @"select ID,cMobile as PhoneNumber,storeName as StoreName,storeManagerName as StoreManagerName,
Province,City,District,Street,Address,saleCode as SaleCode
from Customer (nolock) where id=" + idcus.ToString();
            DataTable dtval = HandleSQL.GetData(cmdsql);
            if (dtval.Rows.Count > 0)
            {
                CustomerINFO cusinfo = new CustomerINFO();
                cusinfo.IDCus = (int)dtval.Rows[0]["ID"];
                cusinfo.mobile = (string)dtval.Rows[0]["PhoneNumber"];
                cusinfo.storeName = (string)dtval.Rows[0]["StoreName"];
                cusinfo.storeManagerName = (string)dtval.Rows[0]["StoreManagerName"];
                cusinfo.province = (string)dtval.Rows[0]["Province"];
                cusinfo.city = (string)dtval.Rows[0]["City"];
                cusinfo.district = (string)dtval.Rows[0]["District"];
                cusinfo.street = (string)dtval.Rows[0]["Street"];
                cusinfo.address = (string)dtval.Rows[0]["Address"];
                cusinfo.saleCode = (string)dtval.Rows[0]["SaleCode"];
                return cusinfo;
            }
            else
            { return null; }
        }

        #endregion 获取用户信息

        #region 获取销售码

        public override Dictionary<string, object> GetSaleCode()
        {
            //var tmp = Common.HandleCookie.GetCookieValue("IDPerson");
            //if (tmp.Length > 0)
            //    Common.HandleCookie.ClearCookie("IDPerson");
            // Common.HandleCookie.SetCookie("IDPerson", "296");

            string saleCode = string.Empty;
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                var openid = HandleCookie.GetCookieValue("openid");
                System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("openid:" + openid, "GetSaleCode");
                string sql = "";
                sql += " DECLARE @IDPerson int";
                sql += string.Format(@" SELECT TOP 1  @IDPerson=IdPerson FROM PersonOpenId WHERE openId='{0}'  ORDER BY dDate DESC", openid);
                sql += @" SELECT TOP 1 saleCode FROM dbo.Person(NOLOCK) WHERE IDPerson = @IDPerson";
                System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("saleCode:" + sql, "GetSaleCode");
                saleCode = HandleSQL.GetDataObj(sql).GetVal_String();
            }
            catch (Exception ex)
            {
                MethodBase.GetCurrentMethod().WriteErrLog(ex.ToString());
                ReturnValue.Get(ex.ToString(), false);
            }
            dic.Add("saleCode", saleCode);
            list.Add(dic);
            System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("saleCode:" + saleCode, "GetSaleCode");
            if (saleCode.Trim().Length <= 0)
            {
                ReturnValue.Get("失败", false);
            }
            return ReturnValue.Get("成功", list, true);
        }

        #endregion 获取销售码
    }

    public class CustomerINFO
    {
        public int IDCus;
        public string mobile;
        public string storeName;
        public string storeManagerName;
        public string province;
        public string city;
        public string district;
        public string street;
        public string address;
        public string saleCode;
    }
}